import SDK from '../../lib/NIM_Web_SDK_v7.9.0.js'
import util from '../../utils/index.js'
export default {
	namespaced: true,
	state: {
		myInfo: {},
		currUserCard: {},
		newFriendList: [],
		sysmsgUnread: {},
		friendList: [],			
		userInfos: [],
		userObject: {}, 		     // 用户信息对象
		msgs: {},
		curSessionId: '',            // 当前会话Id
		sessions: [],
		teamInfos: {},
		teamMembers: {}
	},
	getters: {
	  curMsgs: (state) => {
	    let currSessionMsgs = [];
	    let lastMsgTime = 0;
	    const curSessionId = state.curSessionId;
	    if (state.msgs[curSessionId]) {
	      state.msgs[curSessionId].forEach(msg => {
	        if ((msg.time - lastMsgTime) > 1000 * 60 * 5) {
	          lastMsgTime = msg.time
	          currSessionMsgs.push({
	            type: 'timeTag',
	            text: util.formatDate(msg.time, false)
	          })
	        }
	        currSessionMsgs.push(msg)
	      })     
	    }
	    return currSessionMsgs;
	  }
	},
	mutations: {
		updateMyInfo(state, info) {
			state.myInfo = info;
		},
		setCurrUserCard(state, info) {
			state.currUserCard = info;
		},
		setNewFriendList(state, msg) {
			state.newFriendList.push(msg)
		},
		setUnread(state, msg) {
			state.sysmsgUnread = msg;
		},
		setFriendList(state, msg) {
			state.friendList = msg;
		},
		setUserInfos(state, msg) {
			state.userInfos = msg;
			
			let userObject = state.userObject;
			msg.forEach((user) => {
				let account = user.account;
				if (account) {
					userObject[account] 
					= util.mergeObject(userObject[account], user)
				}
			})
			state.userObject = util.mergeObject(state.userObject, userObject)
		},
		// 把消息放到数组末尾
		putMsg(state, msg) {
			const sessionId = msg.sessionId;
			if (!state.msgs[sessionId]) {
				state.msgs[sessionId] = [];
			}
			state.msgs[sessionId].push(msg);
			state.msgs = {...state.msgs}
		},
		updateMsgs(state, obj) {
			const sessionId = obj.sessionId;
			if (!state.msgs[sessionId]) {
				state.msgs[sessionId] = [];
			}
			state.msgs[sessionId] =
				window.nim.mergeMsgs(state.msgs[sessionId], obj.msgs);
				
			state.msgs = {...state.msgs}
		},
		setCurSessionId(state, id) {
		  state.curSessionId = id;
		},
		setSessions(state, sessions) {
			state.sessions = sessions;
		},
		// 更新群组
		updateTeams (state, teams) {
			let teamInfos = state.teamInfos;
			teams.forEach(team => {
				let teamId = team.teamId
				if (teamId) {
					teamInfos[teamId] = util.mergeObject(teamInfos[teamId], team)
				}	
			})
			state.teamInfos = util.mergeObject(state.teamInfos, teamInfos)
		},
		updateTeamMembers (state, obj) {
			state.teamMembers[obj.teamId] = obj.members;
			state.teamMembers = { ...state.teamMembers }
		}
	},
	actions: {
		connect({ commit, dispatch, state }) {	
			// get 请求，获取token
			uni.request({
				url:  '/v1/test/getChatToken?account=admin'
			}).then((res) => {
				
				window.NIM = SDK.NIM;
				window.nim = SDK.NIM.getInstance({
					debug: false,
					autoMarkRead: false,
					appKey: '4334a5be55b6d82d147be243294e88f2',
					account: 'admin',
					token: res[1].data.token,
					db: false,
					onconnect: () => {
						console.log('连接成功')
						if(/^team-/.test(state.curSessionId)) {
							dispatch('getTeamMembers', state.curSessionId.replace(/^team-/, ''));
						}
					},
					
					// 我的信息
					onmyinfo: (data) => {
						console.log('收到用户信息', data)
						commit('updateMyInfo', data);
					},
					
					// 离线系统通知
					onofflinesysmsgs: (sysMsgs) => {
						console.log('收到离线通知：', sysMsgs);
						for(const msg of sysMsgs) {
							if (msg.type === "applyFriend") {
								commit('setNewFriendList', msg);
							}
						}		
					},
					// 好友列表  friendList
					onfriends: (obj) => {
						console.log(obj)
						commit('setFriendList', obj)
					},
					// 用户名片  userInfos
					onusers: (users) => {
						console.log('收到用户名片', users)
						commit('setUserInfos', users)
					},
					// 未读数
					onsysmsgunread: (sysMsgs) => {
						commit('setUnread', sysMsgs)
					},
					// 未读数
					onsysmsgunread: (sysMsgs) => {
						commit('setUnread', sysMsgs)
					},
					onofflinemsgs: (msgs) => {
						console.log('收到离线消息', msgs);
						commit('updateMsgs', msgs);
					},
					onroamingmsgs: (msgs) => {
						console.log('收到漫游消息', msgs);
						commit('updateMsgs', msgs);
					},
					// 会话列表
					onsessions: (sessions) => {
						console.log('收到会话列表', sessions);
						commit('setSessions', sessions);
					},
					// 群同步
					syncTeams: true,
					onteams: (teams) => {
						console.log('收到群列表', teams);
						commit('updateTeams', teams);
					}
				})		
			})		
		},
		updateMyInfo ({ commit }, option) {
			nim.updateMyInfo({
				...option,
				done: (error, user) => {
					commit('updateMyInfo', user);
				}
			})
		},
		passFriendApply({commit, state}, index) {
			const data = state.newFriendList[index];
			window.nim.passFriendApply({
				idServer: data.idServer,
				account: data.from,
				done: (error, obj) => {
					console.log(error, obj)
					uni.switchTab({
						url: '../index/index'
					})
				}
			})
		},
		// 发送消息
		sendText({ commit }, options) {
			window.nim.sendText({
				scene: 'p2p',
				...options,
				done: (error, msg) => {
					console.log(msg);
					 commit('putMsg', msg);
				}
			})
		},
		// 发送文件
		sendFile({ commit }, options) {
			window.nim.sendFile({
				scene: 'p2p',
				...options,
				done: (error, msg) => {
					console.log(msg);
					commit('putMsg', msg);
				}
			})
		},
		// 设置当前会话
		setCurSession ({ commit }, sessionId) {
		  commit('setCurSessionId', sessionId);
		},
		
		// 群成员获取
		getTeamMembers ({ commit }, teamId) {
		  window.nim && window.nim.getTeamMembers({
			  teamId,
			  done: (error, obj) => {
			  	console.log('收到群成员列表', obj);
				commit('updateTeamMembers', obj);
			  }
		  })
		}
	}
}